<template>
  <div class="editor-box">
    <Toolbar class="editor-toolbar" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
    <Editor
        v-bind="$attrs"
        :defaultConfig="editorConfig"
        mode="default"
        @on-created="editor => editorRef = editor"/>
  </div>
</template>

<script setup lang="ts" name="wangEditor">
/*pnpm add @wangeditor/editor
pnpm add @wangeditor/editor-for-vue@next
*/
import { shallowRef, onBeforeUnmount } from "vue";
import { getAvatarUpload } from "@/api/file";
import { IToolbarConfig, IEditorConfig } from "@wangeditor/editor";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";

// 富文本 DOM 元素
const editorRef = shallowRef();

const toolbarConfig = {
  excludeKeys: []
};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {}
}


type InsertFnTypeImg = (url: string, alt?: string, href?: string) => void;
editorConfig.MENU_CONF["uploadImage"] = {
  async customUpload(file: File, insertFn: InsertFnTypeImg) {
    try {
      const {url} = await getAvatarUpload({file});
      insertFn(url)
    } catch (error) {
      console.log(error);
    }
  }
};


type InsertFnTypeVideo = (url: string, poster?: string) => void;
editorConfig.MENU_CONF["uploadVideo"] = {
  async customUpload(file: File, insertFn: InsertFnTypeVideo) {
    try {
      const {data} = await getAvatarUpload({file});
      insertFn(data.link);
    } catch (error) {
      console.log(error);
    }
  }
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  if (!editorRef.value) return;
  editorRef.value.destroy();
});
</script>

<style scoped lang="less">
/* 富文本组件样式 */
.editor-box {
  height: 500px;
  /* 防止富文本编辑器全屏时 tabs组件 在其层级之上 */
  z-index: 2;
  .editor-toolbar {
    border-bottom: 1px solid #cccccc;
  }
}

</style>
